<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.keyword"
        placeholder="公告标题"
        style="width: 200px"
        class="filter-item"
      />
      <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option label="已发布" value="1" />
        <el-option label="未发布" value="0" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleQuery">
        搜索
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="margin-left: 10px">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="noticeList"
      border
      style="width: 100%"
    >
      <el-table-column prop="title" label="公告标题" />
      <el-table-column label="公告图片" width="120" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.imgUrl"
            :src="baseUrl + scope.row.imgUrl"
            :preview-src-list="[baseUrl + scope.row.imgUrl]"
            fit="cover"
            style="width: 80px; height: 60px; border-radius: 4px;"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="公告内容" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            :icon="scope.row.status === '1' ? 'el-icon-close' : 'el-icon-check'"
            @click="handleToggleStatus(scope.row)"
          >{{ scope.row.status === '1' ? '下架' : '发布' }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item v-if="form.id" label="图片" prop="imgUrl">
          <el-upload
            class="notice-uploader"
            :action="'/api/admin/info/notice/upload'"
            :headers="uploadHeaders"
            :data="{articleId: form.id}"
            name="file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.imgUrl" :src="baseUrl + form.imgUrl" class="notice-image">
            <i v-else class="el-icon-plus notice-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            placeholder="请输入公告内容"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'Notice',
  components: {
    Pagination
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 弹出层标题
      title: '',
      // 是否显示出层
      open: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        status: ''
      },
      // 表单参数
      form: {
        id: undefined,
        title: '',
        content: '',
        status: '0',
        imgUrl: ''
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '公告内容不能为空', trigger: 'blur' }
        ]
      },
      // 公告列表数据
      noticeList: [],
      baseUrl: 'http://localhost:8090', // 后端服务器地址
      uploadHeaders: {
        Authorization: 'Bearer ' + window.localStorage.getItem('token')
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 添加页面刷新时的处理
    window.addEventListener('beforeunload', () => {
      this.getList()
    })
  },
  methods: {
    /** 查询公告列表 */
    async getList() {
      this.loading = true
      try {
        const res = await request({
          url: '/api/admin/info/notice/list',
          method: 'get',
          params: {
            pageNum: this.queryParams.pageNum,
            pageSize: this.queryParams.pageSize,
            keyword: this.queryParams.keyword,
            status: this.queryParams.status
          }
        })
        if (res.code === 200) {
          this.noticeList = res.data.list || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '获取公告列表失败')
        }
      } catch (error) {
        console.error('获取公告列表失败:', error)
        this.$message.error('获取公告列表失败')
      }
      this.loading = false
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        title: '',
        content: '',
        status: '0',
        imgUrl: ''
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加公告'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = { ...row }
      this.open = true
      this.title = '修改公告'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            const method = this.form.id ? 'put' : 'post'
            const res = await request({
              url: '/api/admin/info/notice',
              method: method,
              data: this.form
            })
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.open = false
              this.getList()
            } else {
              this.$message.error(res.message || '操作失败')
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败')
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除题为"' + row.title + '"的数据?', '警告', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: '/api/admin/info/notice/' + row.id,
            method: 'delete'
          })
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      })
    },
    /** 切换状态 */
    async handleToggleStatus(row) {
      try {
        const newStatus = row.status === '1' ? '0' : '1'
        const res = await request({
          url: `/api/admin/info/notice/status/${row.id}/${newStatus}`,
          method: 'put'
        })
        if (res.code === 200) {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        this.$message.error('操作失败')
      }
    },
    /** 上传图片前的校验 */
    beforeUpload(file) {
      // 新增时不允许上传图片
      if (!this.form.id) {
        this.$message.warning('请先保存公告，再上传图片')
        return false
      }

      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    /** 图片上传成功回调 */
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.form.imgUrl = res.data // 数据库存储的是 /notice/xxx.jpg 格式
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.message || '上传失败')
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.notice-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.notice-uploader:hover {
  border-color: #409EFF;
}
.notice-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.notice-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style> 